<?php
$adm_menu = "1";

include("config.php");
if (!isset($_SESSION["auser"]) || $_SESSION["auser"] == "" || $_SESSION['agroup'] != "WEB_ADMIN") header('Location: index.php');


$db_www = new DB($server_username,$server_pass,$server_db,$server,$driver);
$db_rdata = new DB($rdata_server_username,$rdata_server_pass,$rdata_server_db,$rdata_server,$rdata_driver);


if (isset($_REQUEST['month']) && is_numeric($_REQUEST['month'])){
	$month = $_REQUEST['month'];
} else {
	$month = date("m", strtotime("-1 months"));
}


if (isset($_REQUEST['year']) && is_numeric($_REQUEST['year'])){
	$year = $_REQUEST['year'];
} else {
	$year = date("Y");
}
if (isset($_REQUEST['data']) ){
	$data = $_REQUEST['data'];
} else {
	$data = date("Y.m.d");
}
$err = "";
if (isset($_REQUEST["act"])){
	if ($_REQUEST["act"] == "del" && isset($_REQUEST["id"])) {
		//kvieciame trynimo proc
		$sql = "exec web_del_prot_items "
		. "@X02_data='".addslashes_mssql($_REQUEST['id'])."'";		
		$db_rdata->execute($sql);
	} else if ($_REQUEST["act"] == "save" ) {
	  //patikrinam ar gera data
	  if (!validateDate($_POST['data'],'Y.m.d')){
		$err .= "Neteisinga data!";
	  } else {
		  //jei naujas, ar tokios datos dar nera
		  if ($_POST['tp']=='new') {
			$test_q = "SELECT count(*) as cnt FROM [x02_prot] WHERE [X02_data] = '".addslashes_mssql($_POST['data'])."'";	
			$im = $db_rdata->returnInfo($test_q);	
			if ($im['cnt']>0) {	
				$err .= "Protokolas šiai datai jau egzistuoja!";
			}
		  }
	  }
	  $sql = "create table #tt_eilutes(kodas_ps varchar(100),kaina varchar(100));";
	  $db_rdata->execute($sql);	
 
	  //tikrinam ar visos reiksmes skaiciai/tuscia ir terpiam i tt
	  foreach ($_POST as $item=>$val) {
		  if(substr($item,0,1)=='i'){
			if(is_numeric($val) || trim($val)==''){
				$sql = "insert into #tt_eilutes VALUES('".substr($item,1)."','".addslashes_mssql($val)."');";
				$db_rdata->execute($sql);	
			} else {
				$err .= "<br>Neteisinga suma!";
			} 
		  }
	  }
		  if ($err=='') {
		  //kvieciam terpimo/koregavimo procedura
			$sql = "exec web_ins_upd_prot_items "
			. "@X02_data='".addslashes_mssql($_POST['data'])."'";		
			$db_rdata->execute($sql);
		}
	}
}
	
include("header.php");
include("menu.php");





			
?>


<table class="innercont" cellspacing="0" cellpadding="10" border="0">
<tr><td class="leftcol2">




</td><td class="rightcol" colspan="2">


<table width="100%" border="0">

<tr>
<td valign="top">


</td>
</tr>

<tr><td valign="top">
<?php
if (isset($err) && $err != ""){
	echo "<p style='background-color:transparent;color:red;font-weight:bold;font-size:10px;'>".$err."</p>";
}
?>
<script>
if (typeof String.prototype.startsWith != 'function') {
  // see below for better implementation!
  String.prototype.startsWith = function (str){
    return this.indexOf(str) == 0;
  };
}

function delItem(id,month,year){
	var answer = confirm("Ar ištrinti įrašą?");
	if (answer){
		window.location='edit_protocol.php?act=del&month='+month+'&year='+year+'&id='+id ;
	}

}


function isDate(dateStr) { 

    var datePat = /^(\d{4})(.|-)(\d{1,2})(.|-)(\d{1,2})$/; 
    var matchArray = dateStr.match(datePat); 

    if (matchArray == null) { 
        alert('Neteisinga data!');
        return false; 
    } 

    month = matchArray[3]; 
    day = matchArray[5]; 
    year = matchArray[1]; 

    if (month < 1 || month > 12) { 
        alert("Mėnuo turi būti tarp 1 ir 12."); 
        return false; 
    } 

    if (day < 1 || day > 31) { 
        alert("Diena turi būti tarp 1 ir 31."); 
        return false; 
    } 

    if ((month==4 || month==6 || month==9 || month==11) && day==31) { 
        alert("Mėnuo "+month+" neturi 31 dienos!") 
        return false; 
    } 

    if (month == 2) { 
        var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)); 
        if (day > 29 || (day==29 && !isleap)) { 
            alert("Vasaris " + year + " neturi " + day + " dienos!"); 
            return false; 
        } 
    } 
    return true; 
} 

function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

function validateForm(myform){
//ar validi data
dt = document.getElementById("data");
if(!isDate(dt.value)){
	return;
}
//ar skaiciai/tuscia
var arr = document.forms[0].elements;
for (var i = 0; i < arr.length; i++) {
  var el = arr[i];
  // do something with it.
  if (el.name.startsWith('i')){
	if(!isNumber(el.value) && el.value.trim()!=''){
		alert('Neteisinga reikšmė: '+el.value);
		return;
	}
  }
}

myform.submit();
}
</script>
<form method="post" name='forma' action='edit_protocol.php?act=save'>
<input id="month" type="hidden" name="month" value="<?php echo $month?>">
<input id="year" type="hidden" name="year" value="<?php echo $year?>">

<?php
    $sql = 'select * from x01_prot_n';
    $prekes = $db_rdata->returnList($sql);
    $pr = array();
	foreach ($prekes as $preke) {
	   $id = $preke['X01_kodas_ps']; 
	   $pr[$id] = $preke['X01_pav'];
	}
	
	echo '<table cellspacing="0" cellpadding="3"><tr><td style="text-align:right;"></td></tr><tr><td>';
	echo '<table cellspacing="0" cellpadding="3" class="innercont3">';
	echo '<tr><th>Data</th>';
	foreach ($pr as $x=>$xval) {
	   echo '<th>'.htmlspecialchars( $xval).'</th>';
	}
	echo '</tr>';
	$sql = 'select CONVERT(VARCHAR(10),X02_data, 102) as X02_data from x02_prot where year(X02_data) = '.$year.' and month(X02_data)= '.$month.' group by X02_data order by X02_data';
    $datos = $db_rdata->returnList($sql);
	
	foreach ($datos as $dt) {
	  $sql = "select * from x02_prot where X02_data='".$dt['X02_data']."'";
	  $eilute = $db_rdata->returnList($sql);
		$eil = array();
		foreach ($eilute as $preke) {
		   $id = $preke['X02_kodas_ps']; 
		   $eil[$id] = sprintf("%01.3f",$preke['X02_kaina']);
		}	
       	$tmp = '';
		 foreach ($pr as $x=>$xval) {
				if(isset($eil[$x])) {
				   $vv = $eil[$x];
				} else {
				  $vv ='';
				}
				if ((!isset($_REQUEST["act"]) || $_REQUEST["act"]!='edit')|| $data!=$dt['X02_data']){
					$tmp .= '<td style="text-align:right;">'.htmlspecialchars(sprintf("%01.3f",$vv) ).'</td>';
			   } else {
					$tmp .= '<td style="text-align:right;"><input class="inp" type="text" name="i'.trim($x).'" style="width:80px;" value="'.htmlspecialchars($vv ).'"></td>';
			    } 
			}
				if ((!isset($_REQUEST["act"]) || $_REQUEST["act"]!='edit')|| $data!=$dt['X02_data']){
					$tmp .=  "<td class='click' onclick=\"delItem('".$dt['X02_data']."','".$month."','".$year."');return false;\"><img src='img/delete.jpg' width='11' alt='Trinti' title='Trinti'></td>";

				} else {
					$tmp .= '<td valign="top"><input id="data" type="hidden" name="data" value="'.htmlspecialchars($dt['X02_data']).'"><input id="tp" type="hidden" name="tp" value="edit"><input onclick="validateForm('."'forma'".');return false;" class="but bgwhite nopad" type="submit" value="Išsaugoti"></td>';
			    }
	  echo '<tr><td><a class="card" href="edit_protocol.php?act=edit&data='.$dt['X02_data'].'&year='.$year.'&month='.$month.'">'.$dt['X02_data'].'</a></td>'.$tmp.'</tr>';
	}
	if (!isset($_REQUEST["act"]) || $_REQUEST["act"]!='edit'){
		echo '<tr>';
		?>
		<td><input id="data" class="inp" type='text' name="data" style="width:80px;" value="<?php echo htmlspecialchars($data); ?>"></td>
		<?php
		foreach ($pr as $x=>$xval) {
		   echo '<td style="text-align:right;"><input class="inp" type="text" name="i'.trim($x).'" style="width:80px;" value=""></td>';
		}
		?>
		<td valign="top">
		<input id="tp" type="hidden" name="tp" value="new">
		<input class="but bgwhite nopad" type="submit" onclick="validateForm('forma');return false;" value="Išsaugoti"></td>
		<?php
		echo '</tr>';
	}
	echo '</table>';
	?>

</table>
</form>
</td></tr>
</table>



</td></tr>

<tr><td>&nbsp;</td><td>

<Button id='unblockButton' class='but bgwhite nopad' onclick="window.location='<?php echo "aprotocol.php?year=".$year."&month=".$month;?>';return false;">Atgal</Button>

<?php

?>
</td>
<td style="text-align:right;">

</td>
</tr>
</table>

<?php
include("footer.php");
?>